{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                \n",
    "                for n in range(num_layers):\n",
    "                    (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                        cell_fw = cells(size_layer // 2),\n",
    "                        cell_bw = cells(size_layer // 2),\n",
    "                        inputs = encoder_embedded,\n",
    "                        sequence_length = X_seq_len,\n",
    "                        dtype = tf.float32,\n",
    "                        scope = 'bidirectional_rnn_%d'%(n))\n",
    "                    encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "                    \n",
    "                bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n",
    "                bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n",
    "                bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n",
    "                last_state = tuple([bi_lstm_state] * num_layers)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = last_state,\n",
    "                                               dtype = tf.float32)\n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-15-a1c2a26e1bfa>:50: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 15601,  5615, 29690, 29690, 29690, 16154, 22547, 22547,\n",
       "          24217,  3729, 24217, 24217,  3493,  3493,  3493,  3493, 19484,\n",
       "          16880, 28603, 28603, 22409, 22409, 19347,  1932, 14111, 28843,\n",
       "          28843, 19816, 19816, 19816, 26916,  4480,  4480,  4480,  4480,\n",
       "          28082]],\n",
       " \n",
       "        [[    1, 29471, 29471,  2294,  2294,  2294, 22212, 14558, 14558,\n",
       "          26710, 24598, 24598, 15681, 15681, 15681, 15681, 15905, 15905,\n",
       "          15905, 15905, 15905,  8586,  8586,  6491,  6491,  6491, 18662,\n",
       "          18662, 23371, 25562, 25562, 17801, 17801, 16091, 16091, 16091,\n",
       "          20324]],\n",
       " \n",
       "        [[    1, 26174, 28821, 28821, 28821, 12738, 12738, 12738, 12738,\n",
       "           5170,  5170, 28142,  4305, 31621, 31621, 31621,  7803, 29797,\n",
       "          29797, 29797,  2192,  2947,  2947,  2947,  2947, 12268, 19555,\n",
       "          19555, 14105, 14105, 19555, 30502, 14911, 14911, 27759,  4714,\n",
       "            803]],\n",
       " \n",
       "        [[    1,  7008, 15227, 24222, 24222, 11821, 11821, 31941, 31941,\n",
       "          31941, 18974, 18974, 23187,  2331,  2331, 10828,  5962,  5962,\n",
       "           5962, 15774,  5048,  5048,  9939,  9939,  9939,  9939,  9939,\n",
       "           9939,  3574,   423,   423,   423, 30410,  1630,  1630, 22594,\n",
       "           1163]],\n",
       " \n",
       "        [[    1,  1262,  1262, 15376, 15376,  9905, 14789, 23219, 23219,\n",
       "          23219,  3304,  3304,  3304,  3304,  4087, 19465, 19465, 17734,\n",
       "          17734, 15653, 15653, 15653, 15653, 15653, 15653, 11115, 11115,\n",
       "           2418,  2418, 17624, 17624,  1671,  1671,  1671, 17624, 31492,\n",
       "          21315]],\n",
       " \n",
       "        [[    1, 16803,  3316,  3316,  3316, 22010, 22010,  3196,  3196,\n",
       "           3196,  1426,  1426, 15639, 29029, 29029, 12790, 12790, 15817,\n",
       "           6970,  6970,  6970, 20888, 20888, 21140, 21140, 23507, 23507,\n",
       "          13935, 13935, 13935, 28924, 28924, 28924, 31229, 31229, 31229,\n",
       "          31282]],\n",
       " \n",
       "        [[    1, 21582, 21078, 24819, 19118,  1031,  1031,  2523,   566,\n",
       "            566,  4404, 29783,  7583,  7583,  3648,  7583, 24250, 23771,\n",
       "          23771, 24250,  2455, 22139, 25647, 25647, 22139, 25544, 25544,\n",
       "           3589, 26237, 26237, 26237, 11151, 11151, 29638, 17067, 15288,\n",
       "          15288]],\n",
       " \n",
       "        [[    1, 22831, 22831,  2901,  2901,  2901,  2901,  8799,  5962,\n",
       "           5962,  5962, 23948, 18262,  6184, 16047,  6184, 26399, 26399,\n",
       "          23137, 15191, 15191, 14048, 29454, 29454, 29454, 29454, 29454,\n",
       "          11971, 25859, 25859, 24187, 24336, 28015, 19262, 18761, 21083,\n",
       "          18098]],\n",
       " \n",
       "        [[    1,  7484,  7484, 22580, 22580, 15241, 15241,  8799, 11997,\n",
       "          11997, 25166, 12196, 12196, 12196, 12196,  4730,  7142,  7142,\n",
       "           7142,  7142, 15184, 24169, 24169, 24169, 12216, 12216, 12216,\n",
       "          12216, 12216, 12216, 12216, 12216,  2199,  7839,  7839, 27895,\n",
       "          24658]],\n",
       " \n",
       "        [[    1,  2176, 29221, 29221, 31132,  1739,  1739, 13537, 13537,\n",
       "           3169,  3169,  3169,  7550,  6867,  6867,  6867, 21275, 22126,\n",
       "           4675, 22126,  6622,  6622,  6622,  6622, 19638, 30402, 30402,\n",
       "           9715,  9715, 29162,  6876, 27841, 27841, 27841, 18213, 18213,\n",
       "          23982]]], dtype=int32), 10.373104, 0.0]"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:01<00:00,  2.60it/s, accuracy=0.109, cost=6.91] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.85it/s, accuracy=0.113, cost=6.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 7.342525, training avg acc 0.096653\n",
      "epoch 1, testing avg loss 6.822496, testing avg acc 0.121109\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:02<00:00,  2.60it/s, accuracy=0.129, cost=6.3] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.95it/s, accuracy=0.14, cost=6.15] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 6.520037, training avg acc 0.133959\n",
      "epoch 2, testing avg loss 6.319133, testing avg acc 0.142359\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:01<00:00,  2.60it/s, accuracy=0.145, cost=5.78]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.06it/s, accuracy=0.177, cost=5.92]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 6.033985, training avg acc 0.150889\n",
      "epoch 3, testing avg loss 6.045453, testing avg acc 0.152021\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:02<00:00,  2.59it/s, accuracy=0.161, cost=5.29]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.75it/s, accuracy=0.151, cost=5.8] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.665093, training avg acc 0.163101\n",
      "epoch 4, testing avg loss 5.899572, testing avg acc 0.154558\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:00<00:00,  2.60it/s, accuracy=0.187, cost=4.85]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.81it/s, accuracy=0.151, cost=5.73]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 5.361842, training avg acc 0.174137\n",
      "epoch 5, testing avg loss 5.834425, testing avg acc 0.155729\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:52<00:00,  2.64it/s, accuracy=0.208, cost=4.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.20it/s, accuracy=0.167, cost=5.76]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 5.112140, training avg acc 0.185423\n",
      "epoch 6, testing avg loss 5.838683, testing avg acc 0.155074\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:54<00:00,  2.63it/s, accuracy=0.237, cost=4.24]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.95it/s, accuracy=0.156, cost=5.8] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.929491, training avg acc 0.195286\n",
      "epoch 7, testing avg loss 5.851321, testing avg acc 0.155197\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:04<00:00,  2.58it/s, accuracy=0.263, cost=3.98]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.07it/s, accuracy=0.167, cost=5.79]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.775911, training avg acc 0.205225\n",
      "epoch 8, testing avg loss 5.903407, testing avg acc 0.154030\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:04<00:00,  2.59it/s, accuracy=0.272, cost=3.84]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.02it/s, accuracy=0.167, cost=5.92]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.623979, training avg acc 0.217061\n",
      "epoch 9, testing avg loss 5.957799, testing avg acc 0.152714\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:03<00:00,  2.59it/s, accuracy=0.321, cost=3.56]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.96it/s, accuracy=0.167, cost=6.03]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.493582, training avg acc 0.227992\n",
      "epoch 10, testing avg loss 6.038374, testing avg acc 0.150705\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:27<00:00,  2.49it/s, accuracy=0.355, cost=3.35]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.11it/s, accuracy=0.167, cost=6.05]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 4.372293, training avg acc 0.239323\n",
      "epoch 11, testing avg loss 6.095531, testing avg acc 0.148959\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:01<00:00,  2.60it/s, accuracy=0.387, cost=3.21]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.92it/s, accuracy=0.151, cost=6.12]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 4.256957, training avg acc 0.251040\n",
      "epoch 12, testing avg loss 6.170427, testing avg acc 0.147420\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:27<00:00,  2.49it/s, accuracy=0.395, cost=3.12]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.99it/s, accuracy=0.167, cost=6.1] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 4.157085, training avg acc 0.261625\n",
      "epoch 13, testing avg loss 6.228828, testing avg acc 0.146910\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:12<00:00,  2.55it/s, accuracy=0.415, cost=2.99]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:13<00:00,  3.06it/s, accuracy=0.156, cost=6.24]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 4.067402, training avg acc 0.271710\n",
      "epoch 14, testing avg loss 6.302985, testing avg acc 0.145438\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:58<00:00,  2.61it/s, accuracy=0.422, cost=2.89]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.38it/s, accuracy=0.161, cost=6.24]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.982556, training avg acc 0.281437\n",
      "epoch 15, testing avg loss 6.405130, testing avg acc 0.141039\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:48<00:00,  2.66it/s, accuracy=0.463, cost=2.78]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.17it/s, accuracy=0.161, cost=6.3] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.901495, training avg acc 0.291421\n",
      "epoch 16, testing avg loss 6.467974, testing avg acc 0.140785\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:49<00:00,  2.65it/s, accuracy=0.482, cost=2.67]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.16it/s, accuracy=0.151, cost=6.24]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.827627, training avg acc 0.300602\n",
      "epoch 17, testing avg loss 6.530092, testing avg acc 0.140208\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:49<00:00,  2.65it/s, accuracy=0.498, cost=2.58]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.08it/s, accuracy=0.161, cost=6.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.759603, training avg acc 0.309390\n",
      "epoch 18, testing avg loss 6.606641, testing avg acc 0.140471\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:49<00:00,  2.65it/s, accuracy=0.501, cost=2.55]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.14it/s, accuracy=0.156, cost=6.36]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.695875, training avg acc 0.317541\n",
      "epoch 19, testing avg loss 6.681458, testing avg acc 0.139124\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:50<00:00,  2.65it/s, accuracy=0.509, cost=2.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.05it/s, accuracy=0.151, cost=6.37]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.633216, training avg acc 0.325946\n",
      "epoch 20, testing avg loss 6.771697, testing avg acc 0.137953\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [03:44<00:00,  5.62s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.012854616"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
